package com.cabal.common.encrypt;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;

/**
 * AES安全编码组件
 *
 * @version 1.0
 */
@Slf4j
public class AESUtils {

	/**
	 * 密钥算法
	 */
	public static final String KEY_ALGORITHM = "AES";

	/**
	 * 加密/解密算法 / 工作模式 / 填充方式
	 * Java 6支持PKCS5Padding填充方式
	 * Bouncy Castle支持PKCS7Padding填充方式
	 */
	public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

	public static final String CHAR_SET = "UTF-8";


	public static final String ENCRY_KEY = "w5LUvPjD3tyXayCGRHInww==";

	/**
	 * 转换密钥
	 *
	 * @param key 二进制密钥
	 * @return Key 密钥
	 * @throws Exception
	 */
	private static Key toKey(byte[] key) throws Exception {

		// 实例化AES密钥材料
		SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);

		return secretKey;
	}

	/**
	 * 解密
	 *
	 * @param data 待解密数据
	 * @param key  密钥
	 * @return byte[] 解密数据
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] data, byte[] key) throws Exception {

		// 还原密钥
		Key k = toKey(key);

		/*
		 * 实例化
		 * 使用PKCS7Padding填充方式，按如下方式实现
		 * Cipher.getInstance(CIPHER_ALGORITHM, "BC");
		 */
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

		// 初始化，设置为解密模式
		cipher.init(Cipher.DECRYPT_MODE, k);

		// 执行操作
		return cipher.doFinal(data);
	}

	/**
	 * 加密
	 *
	 * @param data 待加密数据
	 * @param key  密钥
	 * @return byte[] 加密数据
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] data, byte[] key) throws Exception {

		// 还原密钥
		Key k = toKey(key);

		/*
		 * 实例化
		 * 使用PKCS7Padding填充方式，按如下方式实现
		 * Cipher.getInstance(CIPHER_ALGORITHM, "BC");
		 */
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

		// 初始化，设置为加密模式
		cipher.init(Cipher.ENCRYPT_MODE, k);

		// 执行操作
		return cipher.doFinal(data);
	}

	/**
	 * 生成密钥 <br>
	 *
	 * @return byte[] 二进制密钥
	 * @throws Exception
	 */
	public static byte[] initKey() throws Exception {

		// 实例化
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);

		/*
		 * AES 要求密钥长度为 128位、192位或 256位
		 */
		kg.init(128);

		// 生成秘密密钥
		SecretKey secretKey = kg.generateKey();

		// 获得密钥的二进制编码形式
		return secretKey.getEncoded();
	}

	public static String initKeyHex() throws Exception {
		byte[] bytes = initKey();
		return Base64.getEncoder().encodeToString(bytes);
	}

	public static String encrypt(String content, String encryKey) {
		if(StringUtils.isBlank(content)){
			return content;
		}
		if(StringUtils.isBlank(encryKey)){
			encryKey = ENCRY_KEY;
		}
		try {
			//注意，这里的key是base64编码过的
			byte[] key = Base64.getDecoder().decode(encryKey.getBytes(CHAR_SET));
			// content Base64解码
			byte[] inputData = content.getBytes(CHAR_SET);
			byte[] outputData = AESCoder.encrypt(inputData, key);
			content = new String(Base64.getEncoder().encode(outputData), CHAR_SET);
			return content;
		} catch (Exception e) {
			log.error("AES解密异常，content=" + content + ", key=" + encryKey, e);
		}
		return content;
	}

	public static String encryptCBC(String data, String key, String iv) {
		try {
			// "算法/模式/补码方式"NoPadding PkcsPadding
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			int blockSize = cipher.getBlockSize();
			byte[] dataBytes = data.getBytes();
			int plaintextLength = dataBytes.length;
			if (plaintextLength % blockSize != 0) {
				plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
			}
			byte[] plaintext = new byte[plaintextLength];
			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
			SecretKey secretKey = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
			IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
			byte[] encrypted = cipher.doFinal(plaintext);
			return new String(Base64.getEncoder().encode(encrypted), CHAR_SET);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String decrypt(String content, String encryKey) {
		if(StringUtils.isBlank(content)){
			return content;
		}
		if(StringUtils.isBlank(encryKey)){
			encryKey = ENCRY_KEY;
		}
		try {
			//注意，这里的key是base64编码过的
			byte[] key = Base64.getDecoder().decode(encryKey.getBytes(CHAR_SET));
			// content Base64解码
			byte[] inputData = Base64.getDecoder().decode(content.getBytes(CHAR_SET));
			byte[] outputData = AESCoder.decrypt(inputData, key);
			if(outputData == null) {
				return content;
			}
			content = new String(outputData, CHAR_SET);
			return content;
		} catch (Exception e) {
			//log.error("AES解密异常，content=" + content + ", key=" + encryKey, e);
		}
		return content;
	}

	public static void main(String[] args) {
		String decrypt = decrypt("mcW4VVmZk3IFR3trFTd07w==", null);
		System.out.println(decrypt);

	}
}
